package com.cj.service.impl;

import com.cj.mapper.AuditLogMapper;
import com.cj.pojo.AuditLog;
import com.cj.pojo.PageBean;
import com.cj.service.AuditLogService;
import com.cj.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class AuditLogServiceImpl implements AuditLogService {
    @Autowired
    private AuditLogMapper auditLogMapper;

    @Override
    public void add(AuditLog auditLog) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        auditLog.setUserId(userId != null ? userId.longValue() : null);
        auditLog.setCreatedAt(LocalDateTime.now());
        auditLogMapper.add(auditLog);
    }

    @Override
    public void delete(Long id) {
        auditLogMapper.delete(id);
    }

    @Override
    public PageBean<AuditLog> list(Long userId, String actionType, 
        LocalDateTime startTime, LocalDateTime endTime,
        Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<AuditLog> logs = auditLogMapper.findByCriteria(userId, actionType, startTime, endTime, 
                                                          (pageNum - 1) * pageSize, pageSize);
        Page<AuditLog> p = (Page<AuditLog>) logs;
        return new PageBean<>(p.getTotal(), p.getResult());
    }
}
